<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>客户信息管理系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        accent: '#367CFF',
                        secondary: '#6B7280',
                        success: '#00B42A',
                        warning: '#FF7D00',
                        danger: '#F53F3F',
                        info: '#86909C',
                        light: '#F2F3F5',
                        dark: '#1D2129',
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                    boxShadow: {
                        'blue': '0 4px 20px 0 rgba(22, 93, 255, 0.1)',
                    }
                },
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .error-message {
                color: #F53F3F;
                font-size: 0.75rem;
                margin-top: 0.25rem;
            }
            .modal-backdrop {
                backdrop-filter: blur(4px);
            }
            .animate-fade-in {
                animation: fadeIn 0.3s ease-in-out;
            }
            @keyframes fadeIn {
                from { opacity: 0; }
                to { opacity: 1; }
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-inter text-gray-800 min-h-screen">
    <!-- 顶部导航栏 -->
    <header class="bg-white shadow-sm sticky top-0 z-50">
        <div class="container mx-auto px-4 py-3 flex justify-between items-center">
            <div class="flex items-center space-x-2">
                <i class="fa fa-users text-primary text-2xl"></i>
                <h1 class="text-xl font-bold text-primary">客户信息管理系统</h1>
            </div>
            <div class="flex items-center space-x-4">
                <div class="hidden md:flex items-center space-x-1 text-sm text-gray-600">
                    <i class="fa fa-calendar-o"></i>
                    <span id="current-date">2023年6月15日 星期四</span>
                </div>
                <div class="flex items-center space-x-2 text-sm">
                    <i class="fa fa-user-circle-o text-primary"></i>
                    <span>管理员</span>
                </div>
            </div>
        </div>
    </header>

    <!-- 主内容区 -->
    <main class="container mx-auto px-4 py-6">
        <!-- 统计卡片 -->
        <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
            <div class="bg-white rounded-xl shadow-blue p-6 flex items-center">
                <div class="w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center mr-4">
                    <i class="fa fa-users text-primary text-xl"></i>
                </div>
                <div>
                    <p class="text-gray-500 text-sm">客户总数</p>
                    <p class="text-2xl font-bold" id="total-customers">0</p>
                </div>
            </div>
            <div class="bg-white rounded-xl shadow-blue p-6 flex items-center">
                <div class="w-12 h-12 rounded-full bg-success/10 flex items-center justify-center mr-4">
                    <i class="fa fa-id-card text-success text-xl"></i>
                </div>
                <div>
                    <p class="text-gray-500 text-sm">今日新增</p>
                    <p class="text-2xl font-bold" id="new-today">0</p>
                </div>
            </div>
            <div class="bg-white rounded-xl shadow-blue p-6 flex items-center">
                <div class="w-12 h-12 rounded-full bg-warning/10 flex items-center justify-center mr-4">
                    <i class="fa fa-phone text-warning text-xl"></i>
                </div>
                <div>
                    <p class="text-gray-500 text-sm">待跟进</p>
                    <p class="text-2xl font-bold" id="to-follow">0</p>
                </div>
            </div>
            <div class="bg-white rounded-xl shadow-blue p-6 flex items-center">
                <div class="w-12 h-12 rounded-full bg-accent/10 flex items-center justify-center mr-4">
                    <i class="fa fa-bar-chart text-accent text-xl"></i>
                </div>
                <div>
                    <p class="text-gray-500 text-sm">活跃度</p>
                    <p class="text-2xl font-bold" id="activity-rate">0%</p>
                </div>
            </div>
        </div>

        <!-- 搜索和筛选区域 -->
        <div class="bg-white rounded-xl shadow-blue p-6 mb-6">
            <div class="grid grid-cols-1 md:grid-cols-5 gap-6">
                <div class="relative">
                    <label class="block text-sm font-medium text-gray-700 mb-1">客户姓名 <span class="text-red-500">*</span></label>
                    <div class="relative">
                        <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-400">
                            <i class="fa fa-user"></i>
                        </span>
                        <input type="text" id="name-filter" placeholder="请输入客户姓名" class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all" required>
                    </div>
                </div>
                <div class="relative">
                    <label class="block text-sm font-medium text-gray-700 mb-1">客户编号</label>
                    <div class="relative">
                        <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-400">
                            <i class="fa fa-hashtag"></i>
                        </span>
                        <input type="text" id="id-filter" placeholder="请输入客户编号" class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all">
                    </div>
                </div>
                <div class="relative">
                    <label class="block text-sm font-medium text-gray-700 mb-1">身份证号 <span class="text-red-500">*</span></label>
                    <div class="relative">
                        <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-400">
                            <i class="fa fa-id-card"></i>
                        </span>
                        <input type="text" id="idcard-filter" placeholder="请输入18位身份证号" class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all" required>
                        <div id="idcard-error" class="error-message hidden"></div>
                    </div>
                </div>
                <div class="relative">
                    <label class="block text-sm font-medium text-gray-700 mb-1">联系电话 <span class="text-red-500">*</span></label>
                    <div class="relative">
                        <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-400">
                            <i class="fa fa-phone"></i>
                        </span>
                        <input type="text" id="phone-filter" placeholder="请输入11位手机号码" class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all" required>
                        <div id="phone-error" class="error-message hidden"></div>
                    </div>
                </div>
                <div class="relative">
                    <label class="block text-sm font-medium text-gray-700 mb-1">联系住址</label>
                    <div class="relative">
                        <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-400">
                            <i class="fa fa-map-marker"></i>
                        </span>
                        <input type="text" id="address-filter" placeholder="请输入联系住址" class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all">
                    </div>
                </div>
            </div>

            <div class="mt-4 flex justify-end space-x-3">
                <button id="reset-btn" class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors">
                    重置
                </button>
                <button id="search-btn" class="bg-primary text-white px-4 py-2 rounded-lg hover:bg-accent transition-colors shadow-md">
                    <i class="fa fa-search mr-2"></i>搜索
                </button>
            </div>
        </div>

        <!-- 表格区域 -->
        <div class="bg-white rounded-xl shadow-blue p-6 mb-6">
            <div class="flex justify-between items-center mb-6">
                <h2 class="text-lg font-semibold">客户信息列表</h2>
                <button id="add-customer-btn" class="bg-primary text-white px-4 py-2 rounded-lg hover:bg-accent transition-colors shadow-md">
                    <i class="fa fa-plus mr-2"></i>新增客户
                </button>
            </div>

            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">客户编号</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">客户姓名</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">身份证号</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">联系电话</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">联系地址</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">创建时间</th>
                            <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200" id="customers-table-body">
                        <!-- 表格内容将通过JavaScript动态生成 -->
                        <tr class="text-center">
                            <td colspan="7" class="px-6 py-12 text-gray-500">
                                <div class="flex flex-col items-center">
                                    <i class="fa fa-search text-4xl mb-4 text-gray-300"></i>
                                    <p>暂无客户数据，请添加或搜索客户</p>
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <!-- 分页 -->
            <div class="flex justify-between items-center mt-6">
                <div class="text-sm text-gray-500">
                    显示 <span id="start-index">0</span> 到 <span id="end-index">0</span> 条，共 <span id="total-count">0</span> 条记录
                </div>
                <div class="flex space-x-2">
                    <button id="prev-page" class="px-3 py-1 border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                        <i class="fa fa-chevron-left"></i>
                    </button>
                    <button id="next-page" class="px-3 py-1 border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                        <i class="fa fa-chevron-right"></i>
                    </button>
                </div>
            </div>
        </div>
    </main>

    <!-- 页脚 -->
    <footer class="bg-white border-t border-gray-200 py-4">
        <div class="container mx-auto px-4 text-center text-gray-500 text-sm">
            <p>© 2023 客户信息管理系统 | 版权所有</p>
        </div>
    </footer>

    <!-- 客户信息模态框 -->
    <div id="customer-modal" class="fixed inset-0 z-50 flex items-center justify-center hidden">
        <div class="absolute inset-0 bg-black bg-opacity-50 modal-backdrop" id="modal-backdrop"></div>
        <div class="relative bg-white rounded-xl shadow-lg w-full max-w-2xl mx-4 transform scale-95 transition-all duration-300" id="modal-content-container">
            <div class="p-6">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-lg font-semibold" id="modal-title">客户信息</h3>
                    <button id="close-modal" class="text-gray-400 hover:text-gray-600">
                        <i class="fa fa-times text-xl"></i>
                    </button>
                </div>
                <div id="modal-content" class="mb-6">
                    <!-- 模态框内容将通过JavaScript动态生成 -->
                </div>
                <div class="flex justify-end space-x-3">
                    <button id="cancel-customer" class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors">
                        取消
                    </button>
                    <button id="save-customer" class="bg-primary text-white px-4 py-2 rounded-lg hover:bg-accent transition-colors shadow-md">
                        保存
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 删除确认模态框 -->
    <div id="delete-modal" class="fixed inset-0 z-50 flex items-center justify-center hidden">
        <div class="absolute inset-0 bg-black bg-opacity-50 modal-backdrop"></div>
        <div class="relative bg-white rounded-xl shadow-lg w-full max-w-md mx-4 transform scale-95 transition-all duration-300">
            <div class="p-6">
                <div class="text-center mb-4">
                    <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-danger/10 mb-4">
                        <i class="fa fa-exclamation-triangle text-danger text-2xl"></i>
                    </div>
                    <h3 class="text-lg font-semibold">确认删除</h3>
                    <p class="text-gray-500 mt-2">您确定要删除该客户信息吗？此操作不可撤销。</p>
                </div>
                <div class="flex justify-center space-x-3">
                    <button id="cancel-delete" class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors">
                        取消
                    </button>
                    <button id="confirm-delete" class="bg-danger text-white px-4 py-2 rounded-lg hover:bg-red-600 transition-colors shadow-md">
                        确认删除
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 通知组件 -->
    <div id="notification" class="fixed top-4 right-4 z-50 max-w-xs bg-white rounded-lg shadow-lg p-4 transform translate-x-full transition-transform duration-300 flex items-start">
        <div id="notification-icon" class="w-8 h-8 rounded-full flex items-center justify-center mr-3 bg-primary/10">
            <i class="fa fa-info text-primary"></i>
        </div>
        <div class="flex-1">
            <h4 id="notification-title" class="font-medium text-gray-900">通知标题</h4>
            <p id="notification-message" class="text-sm text-gray-500 mt-1">通知内容将显示在这里...</p>
        </div>
        <button id="close-notification" class="text-gray-400 hover:text-gray-600 ml-2">
            <i class="fa fa-times"></i>
        </button>
    </div>

    <script>
        // 当前页码和每页显示数量
        let currentPage = 1;
        const pageSize = 10;
        let currentCustomerId = null;
        let currentCustomerData = null;

        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', function() {
            // 设置当前日期
            setCurrentDate();

            // 初始化事件监听
            initEventListeners();

            // 初始加载客户数据
            loadCustomers();
        });

        // 设置当前日期
        function setCurrentDate() {
            const now = new Date();
            const options = { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long' };
            document.getElementById('current-date').textContent = now.toLocaleDateString('zh-CN', options);
        }

        // 初始化事件监听
        function initEventListeners() {
            // 搜索按钮点击事件
            document.getElementById('search-btn').addEventListener('click', searchCustomers);

            // 重置按钮点击事件
            document.getElementById('reset-btn').addEventListener('click', resetFilters);

            // 新增客户按钮点击事件
            document.getElementById('add-customer-btn').addEventListener('click', addNewCustomer);

            // 关闭模态框按钮点击事件
            document.getElementById('close-modal').addEventListener('click', closeCustomerModal);
            document.getElementById('modal-backdrop').addEventListener('click', closeCustomerModal);
            document.getElementById('cancel-customer').addEventListener('click', closeCustomerModal);

            // 保存客户按钮点击事件
            document.getElementById('save-customer').addEventListener('click', saveCustomer);

            // 删除确认模态框按钮点击事件
            document.getElementById('cancel-delete').addEventListener('click', closeDeleteModal);
            document.getElementById('confirm-delete').addEventListener('click', confirmDeleteCustomer);

            // 关闭通知按钮点击事件
            document.getElementById('close-notification').addEventListener('click', closeNotification);

            // 分页按钮点击事件
            document.getElementById('prev-page').addEventListener('click', prevPage);
            document.getElementById('next-page').addEventListener('click', nextPage);

            // 表单验证事件
            document.getElementById('idcard-filter').addEventListener('input', validateIdCard);
            document.getElementById('phone-filter').addEventListener('input', validatePhone);
        }

        // 加载客户数据
        async function loadCustomers() {
            try {
                showLoadingIndicator();

                // 获取筛选条件
                const name = document.getElementById('name-filter').value.trim();
                const id = document.getElementById('id-filter').value.trim();
                const idCard = document.getElementById('idcard-filter').value.trim();
                const phone = document.getElementById('phone-filter').value.trim();
                const address = document.getElementById('address-filter').value.trim();

                // 构建查询参数（调整为/users接口）
                let queryParams = `?page=${currentPage}&pageSize=${pageSize}`;
                if (name) queryParams += `&name=${encodeURIComponent(name)}`;
                if (id) queryParams += `&id=${encodeURIComponent(id)}`;
                if (idCard) queryParams += `&pid=${encodeURIComponent(idCard)}`; // 注意：后端使用pid参数
                if (phone) queryParams += `&phone=${encodeURIComponent(phone)}`;
                if (address) queryParams += `&address=${encodeURIComponent(address)}`;

                // 调整API路径为/api/users
                const response = await fetch(`http://localhost:3000/api/users${queryParams}`);
                if (!response.ok) {
                    throw new Error('获取客户数据失败');
                }

                const result = await response.json();
                const customers = result.data || [];
                const totalCount = result.total || 0;

                // 更新表格内容
                updateCustomersTable(customers);

                // 更新分页信息
                updatePagination(totalCount);

                // 更新统计卡片
                updateStats(customers, totalCount);

                hideLoadingIndicator();
            } catch (error) {
                hideLoadingIndicator();
                showNotification('错误', '加载客户数据失败，请稍后再试', 'error');
                console.error('加载客户数据失败:', error);
            }
        }

        // 搜索客户
        function searchCustomers() {
            // 验证必填字段
            const name = document.getElementById('name-filter').value.trim();
            const idCard = document.getElementById('idcard-filter').value.trim();
            const phone = document.getElementById('phone-filter').value.trim();

            if (!name) {
                showNotification('提示', '请输入客户姓名', 'warning');
                return;
            }

            if (!idCard) {
                showNotification('提示', '请输入身份证号', 'warning');
                return;
            }

            if (!phone) {
                showNotification('提示', '请输入联系电话', 'warning');
                return;
            }

            // 重置页码并加载数据
            currentPage = 1;
            loadCustomers();
        }

        // 重置筛选条件
        function resetFilters() {
            document.getElementById('name-filter').value = '';
            document.getElementById('id-filter').value = '';
            document.getElementById('idcard-filter').value = '';
            document.getElementById('phone-filter').value = '';
            document.getElementById('address-filter').value = '';

            // 清除错误提示
            document.getElementById('idcard-error').classList.add('hidden');
            document.getElementById('phone-error').classList.add('hidden');

            // 重置页码并加载数据
            currentPage = 1;
            loadCustomers();
        }

        // 新增客户
        async function addNewCustomer() {
            try {
                // 直接创建新客户，无需获取ID（后端自动生成）
                const newCustomer = {
                    name: '',
                    pid: '',
                    phone: '',
                    address: ''
                };

                openCustomerModal(newCustomer, 'edit');
            } catch (error) {
                console.error('新增客户失败:', error);
                showNotification('错误', '准备新增客户失败，请稍后再试', 'error');
            }
        }

        // 打开客户模态框
        function openCustomerModal(customer, mode) {
            const modal = document.getElementById('customer-modal');
            const modalTitle = document.getElementById('modal-title');
            const modalContent = document.getElementById('modal-content');
            const saveBtn = document.getElementById('save-customer');

            if (!customer) return;

            currentCustomerData = { ...customer };

            if (mode === 'view') {
                modalTitle.textContent = '查看客户信息';
                saveBtn.style.display = 'none';

                modalContent.innerHTML = `
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">客户编号</label>
                            <div class="mt-1 p-2 bg-gray-50 rounded-lg border border-gray-200">
                                <span class="text-sm text-gray-900">${customer.id}</span>
                            </div>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">姓名</label>
                            <div class="mt-1 p-2 bg-gray-50 rounded-lg border border-gray-200">
                                <span class="text-sm text-gray-900">${customer.name}</span>
                            </div>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">身份证号</label>
                            <div class="mt-1 p-2 bg-gray-50 rounded-lg border border-gray-200">
                                <span class="text-sm text-gray-900">${customer.pid}</span>
                            </div>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">联系电话</label>
                            <div class="mt-1 p-2 bg-gray-50 rounded-lg border border-gray-200">
                                <span class="text-sm text-gray-900">${customer.phone}</span>
                            </div>
                        </div>
                        <div class="md:col-span-2">
                            <label class="block text-sm font-medium text-gray-700 mb-1">联系地址</label>
                            <div class="mt-1 p-2 bg-gray-50 rounded-lg border border-gray-200 ${!customer.address ? 'text-gray-400' : ''}">
                                <span class="text-sm text-gray-900">${customer.address || '未填写'}</span>
                            </div>
                        </div>
                        <div class="md:col-span-2">
                            <label class="block text-sm font-medium text-gray-700 mb-1">创建时间</label>
                            <div class="mt-1 p-2 bg-gray-50 rounded-lg border border-gray-200">
                                <span class="text-sm text-gray-900">${formatDate(customer.create_time)}</span>
                            </div>
                        </div>
                    </div>
                `;
            } else if (mode === 'edit') {
                modalTitle.textContent = '编辑客户信息';
                saveBtn.style.display = 'inline-block';

                modalContent.innerHTML = `
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">客户编号</label>
                            <div class="mt-1 p-2 bg-gray-50 rounded-lg border border-gray-200">
                                <span class="text-sm text-gray-900">${customer.id || '系统自动生成'}</span>
                            </div>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">姓名 <span class="text-red-500">*</span></label>
                            <input type="text" value="${customer.name}" class="mt-1 w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary" required>
                            <div class="error-message" id="modal-name-error"></div>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">身份证号 <span class="text-red-500">*</span></label>
                            <input type="text" value="${customer.pid}" class="mt-1 w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary" required>
                            <div class="error-message" id="modal-idcard-error"></div>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">联系电话 <span class="text-red-500">*</span></label>
                            <input type="text" value="${customer.phone}" class="mt-1 w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary" required>
                            <div class="error-message" id="modal-phone-error"></div>
                        </div>
                        <div class="md:col-span-2">
                            <label class="block text-sm font-medium text-gray-700 mb-1">联系地址 (选填)</label>
                            <textarea class="mt-1 w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary" rows="2">${customer.address || ''}</textarea>
                        </div>
                    </div>
                `;
            }

            modal.classList.remove('hidden');
            // 添加淡入动画
            setTimeout(() => {
                document.getElementById('modal-content-container').classList.add('scale-100');
                document.getElementById('modal-content-container').classList.remove('scale-95');
            }, 10);
        }

        // 关闭客户模态框
        function closeCustomerModal() {
            const modalContentContainer = document.getElementById('modal-content-container');
            modalContentContainer.classList.remove('scale-100');
            modalContentContainer.classList.add('scale-95');

            setTimeout(() => {
                document.getElementById('customer-modal').classList.add('hidden');
                currentCustomerData = null;
            }, 300);
        }

        // 保存客户信息
        async function saveCustomer() {
            try {
                // 获取表单数据
                const inputs = document.querySelectorAll('#modal-content input, #modal-content textarea');
                const formData = {
                    id: currentCustomerData.id,
                    name: inputs[0].value.trim(),
                    pid: inputs[1].value.trim(), // 身份证号对应后端pid字段
                    phone: inputs[2].value.trim(),
                    address: inputs[3].value.trim()
                };

                // 验证表单
                if (!formData.name) {
                    document.getElementById('modal-name-error').textContent = '请输入客户姓名';
                    document.getElementById('modal-name-error').classList.remove('hidden');
                    return;
                } else {
                    document.getElementById('modal-name-error').classList.add('hidden');
                }

                if (!formData.pid) {
                    document.getElementById('modal-idcard-error').textContent = '请输入身份证号';
                    document.getElementById('modal-idcard-error').classList.remove('hidden');
                    return;
                } else if (!validateIdCardFormat(formData.pid)) {
                    document.getElementById('modal-idcard-error').textContent = '请输入有效的18位身份证号';
                    document.getElementById('modal-idcard-error').classList.remove('hidden');
                    return;
                } else {
                    document.getElementById('modal-idcard-error').classList.add('hidden');
                }

                if (!formData.phone) {
                    document.getElementById('modal-phone-error').textContent = '请输入联系电话';
                    document.getElementById('modal-phone-error').classList.remove('hidden');
                    return;
                } else if (!validatePhoneFormat(formData.phone)) {
                    document.getElementById('modal-phone-error').textContent = '请输入有效的11位手机号码';
                    document.getElementById('modal-phone-error').classList.remove('hidden');
                    return;
                } else {
                    document.getElementById('modal-phone-error').classList.add('hidden');
                }

                let response;
                if (formData.id) {
                    // 更新客户（PUT /api/users）
                    response = await fetch(`http://localhost:3000/api/users`, {
                        method: 'PUT',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(formData)
                    });
                } else {
                    // 新增客户（POST /api/users）
                    response = await fetch('http://localhost:3000/api/users', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(formData)
                    });
                }

                if (!response.ok) {
                    throw new Error('保存客户信息失败');
                }

                const result = await response.json();

                // 关闭模态框
                closeCustomerModal();

                // 刷新数据
                loadCustomers();

                // 显示成功提示
                showNotification('成功', formData.id ? '客户信息更新成功' : '客户信息添加成功', 'success');
            } catch (error) {
                console.error('保存客户信息失败:', error);
                showNotification('错误', '保存客户信息失败，请稍后再试', 'error');
            }
        }

        // 打开删除确认模态框
        function openDeleteModal(customerId) {
            currentCustomerId = customerId;
            document.getElementById('delete-modal').classList.remove('hidden');
            // 添加淡入动画
            setTimeout(() => {
                document.querySelector('#delete-modal > div').classList.add('scale-100');
                document.querySelector('#delete-modal > div').classList.remove('scale-95');
            }, 10);
        }

        // 关闭删除确认模态框
        function closeDeleteModal() {
            const modal = document.querySelector('#delete-modal > div');
            modal.classList.remove('scale-100');
            modal.classList.add('scale-95');

            setTimeout(() => {
                document.getElementById('delete-modal').classList.add('hidden');
                currentCustomerId = null;
            }, 300);
        }

        // 确认删除客户
        async function confirmDeleteCustomer() {
            try {
                if (!currentCustomerId) return;

                const response = await fetch(`http://localhost:3000/api/users/${currentCustomerId}`, {
                    method: 'DELETE'
                });

                if (!response.ok) {
                    throw new Error('删除客户信息失败');
                }

                // 关闭模态框
                closeDeleteModal();

                // 刷新数据
                loadCustomers();

                // 显示成功提示
                showNotification('成功', '客户信息已成功删除', 'success');
            } catch (error) {
                console.error('删除客户信息失败:', error);
                showNotification('错误', '删除客户信息失败，请稍后再试', 'error');
            }
        }

        // 更新客户表格
        function updateCustomersTable(customers) {
            const tableBody = document.getElementById('customers-table-body');

            if (customers.length === 0) {
                tableBody.innerHTML = `
                    <tr class="text-center">
                        <td colspan="7" class="px-6 py-12 text-gray-500">
                            <div class="flex flex-col items-center">
                                <i class="fa fa-search text-4xl mb-4 text-gray-300"></i>
                                <p>暂无符合条件的客户数据</p>
                            </div>
                        </td>
                    </tr>
                `;
                return;
            }

            let html = '';
            customers.forEach(customer => {
                html += `
                    <tr class="hover:bg-gray-50 transition-colors">
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm font-medium text-gray-900">${customer.id}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-900">${customer.name}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-900">${customer.pid}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-900">${customer.phone}</div>
                        </td>
                        <td class="px-6 py-4">
                            <div class="text-sm text-gray-900">${customer.address || '未填写'}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            ${formatDate(customer.create_time)}
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                            <button onclick="openCustomerModal(${JSON.stringify(customer)}, 'view')" class="text-gray-600 hover:text-primary mr-3">
                                <i class="fa fa-eye"></i>
                            </button>
                            <button onclick="openCustomerModal(${JSON.stringify(customer)}, 'edit')" class="text-gray-600 hover:text-primary mr-3">
                                <i class="fa fa-pencil"></i>
                            </button>
                            <button onclick="openDeleteModal('${customer.id}')" class="text-gray-600 hover:text-danger">
                                <i class="fa fa-trash"></i>
                            </button>
                        </td>
                    </tr>
                `;
            });

            tableBody.innerHTML = html;
        }

        // 更新分页信息
        function updatePagination(totalCount) {
            const totalPages = Math.ceil(totalCount / pageSize);
            const startIndex = (currentPage - 1) * pageSize + 1;
            const endIndex = Math.min(currentPage * pageSize, totalCount);

            document.getElementById('start-index').textContent = totalCount > 0 ? startIndex : 0;
            document.getElementById('end-index').textContent = endIndex;
            document.getElementById('total-count').textContent = totalCount;

            // 更新分页按钮状态
            document.getElementById('prev-page').disabled = currentPage === 1;
            document.getElementById('next-page').disabled = currentPage >= totalPages;
        }

        // 更新统计卡片
        function updateStats(customers, totalCount) {
            document.getElementById('total-customers').textContent = totalCount;

            // 模拟今日新增数据
            const newToday = Math.floor(Math.random() * 10);
            document.getElementById('new-today').textContent = newToday;

            // 模拟待跟进数据
            const toFollow = Math.floor(Math.random() * 20);
            document.getElementById('to-follow').textContent = toFollow;

            // 模拟活跃度数据
            const activityRate = Math.floor(Math.random() * 100);
            document.getElementById('activity-rate').textContent = `${activityRate}%`;
        }

        // 上一页
        function prevPage() {
            if (currentPage > 1) {
                currentPage--;
                loadCustomers();
            }
        }

        // 下一页
        function nextPage() {
            const totalCount = parseInt(document.getElementById('total-count').textContent);
            const totalPages = Math.ceil(totalCount / pageSize);

            if (currentPage < totalPages) {
                currentPage++;
                loadCustomers();
            }
        }

        // 显示加载指示器
        function showLoadingIndicator() {
            const tableBody = document.getElementById('customers-table-body');
            tableBody.innerHTML = `
                <tr class="text-center">
                    <td colspan="7" class="px-6 py-12 text-gray-500">
                        <div class="flex flex-col items-center">
                            <i class="fa fa-circle-o-notch fa-spin text-4xl mb-4 text-primary"></i>
                            <p>正在加载数据...</p>
                        </div>
                    </td>
                </tr>
            `;
        }

        // 隐藏加载指示器
        function hideLoadingIndicator() {
            // 加载完成后不需要特别处理，表格内容会被更新
        }

        // 显示通知
        function showNotification(title, message, type = 'info') {
            const notification = document.getElementById('notification');
            const notificationTitle = document.getElementById('notification-title');
            const notificationMessage = document.getElementById('notification-message');
            const notificationIcon = document.getElementById('notification-icon');

            // 设置通知内容
            notificationTitle.textContent = title;
            notificationMessage.textContent = message;

            // 设置通知类型样式
            notificationIcon.className = 'w-8 h-8 rounded-full flex items-center justify-center mr-3';
            let iconClass = 'fa fa-info';

            if (type === 'success') {
                notificationIcon.classList.add('bg-success/10');
                iconClass = 'fa fa-check';
            } else if (type === 'warning') {
                notificationIcon.classList.add('bg-warning/10');
                iconClass = 'fa fa-exclamation';
            } else if (type === 'error') {
                notificationIcon.classList.add('bg-danger/10');
                iconClass = 'fa fa-times';
            } else {
                notificationIcon.classList.add('bg-primary/10');
            }

            notificationIcon.innerHTML = `<i class="${iconClass} text-${type === 'error' ? 'danger' : type === 'warning' ? 'warning' : type === 'success' ? 'success' : 'primary'}"></i>`;

            // 显示通知
            notification.classList.remove('translate-x-full');

            // 3秒后自动关闭
            setTimeout(closeNotification, 3000);
        }

        // 关闭通知
        function closeNotification() {
            const notification = document.getElementById('notification');
            notification.classList.add('translate-x-full');
        }

        // 身份证验证
        function validateIdCard() {
            const idCardInput = document.getElementById('idcard-filter');
            const errorElement = document.getElementById('idcard-error');
            const idCard = idCardInput.value.trim();

            if (!idCard) {
                errorElement.textContent = '请输入身份证号';
                errorElement.classList.remove('hidden');
                return false;
            }

            if (!validateIdCardFormat(idCard)) {
                errorElement.textContent = '请输入有效的18位身份证号';
                errorElement.classList.remove('hidden');
                return false;
            }

            errorElement.classList.add('hidden');
            return true;
        }

        // 手机号验证
        function validatePhone() {
            const phoneInput = document.getElementById('phone-filter');
            const errorElement = document.getElementById('phone-error');
            const phone = phoneInput.value.trim();

            if (!phone) {
                errorElement.textContent = '请输入联系电话';
                errorElement.classList.remove('hidden');
                return false;
            }

            if (!validatePhoneFormat(phone)) {
                errorElement.textContent = '请输入有效的11位手机号码';
                errorElement.classList.remove('hidden');
                return false;
            }

            errorElement.classList.add('hidden');
            return true;
        }

        // 身份证格式验证（简化版）
        function validateIdCardFormat(idCard) {
            // 简单验证18位长度
            return /^\d{17}[\dXx]$/.test(idCard);
        }

        // 手机号格式验证
        function validatePhoneFormat(phone) {
            return /^1[3-9]\d{9}$/.test(phone);
        }

        // 格式化日期
        function formatDate(dateString) {
            if (!dateString) return '';

            const date = new Date(dateString);
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');

            return `${year}-${month}-${day} ${hours}:${minutes}`;
        }
    </script>
</body>
</html>